package cn.pzaily.fealetter.service.impl;

import cn.pzaily.crab.tools.http.enumeration.AppHttpCodeEnum;
import cn.pzaily.crab.tools.http.result.ResponseResult;
import cn.pzaily.crab.tools.http.utils.HttpClient;
import cn.pzaily.crab.tools.core.utils.StringUtils;
import cn.pzaily.fealetter.dto.BatchParamsDTO;
import cn.pzaily.fealetter.dto.ParamsDTO;
import cn.pzaily.fealetter.dto.base.BaseParamsDTO;
import cn.pzaily.fealetter.service.SendService;
import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.text.ParseException;

/**
 * @PackageName: cn.pzaily.fealetter.service.impl
 * @Description:
 * @Author: Pang
 * @Date: 2021-11-22 22:47
 */

public class SendServiceImpl implements SendService {

    private String send = "/send";
    private String batchSend = "/batchSend";
    private String domain;
    private boolean auth;
    private String accessKeyId;
    private String accessKeySecret;

    @Override
    public ResponseResult send(ParamsDTO paramsDTO) {
        return send(paramsDTO, domain + send);
    }

    @Override
    public ResponseResult batchSend(BatchParamsDTO batchParamsDTO) {
        return send(batchParamsDTO, domain + batchSend);
    }


    private ResponseResult send(BaseParamsDTO dto, String url) {
        // TODO 短信接收SDK，通过HttpClient发送请求到短信服务接收端口
        if (StringUtils.isEmpty(this.domain)) {
            return ResponseResult.errorResult("domain 不能为空");
        }
        dto.setAccessKeyId(this.accessKeyId);
        if (auth) {
            if (StringUtils.isEmpty(this.accessKeyId) || StringUtils.isEmpty(this.accessKeySecret)) {
                return ResponseResult.errorResult("accessKey 不能为空");
            }
            dto.setEncryption(this.accessKeySecret);
            dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        }

        HttpClient client = new HttpClient(url);
        client.addHeader("Content-Type", "application/json; charset=UTF-8");
        client.setXmlParam(JSON.toJSONString(dto));
        try {
            client.post();
            if (client.getStatusCode() == AppHttpCodeEnum.SUCCESS.getCode()) {
                String content = client.getContent();
                return JSON.parseObject(content, ResponseResult.class);
            }

        } catch (IOException | ParseException e) {
            return ResponseResult.errorResult(e.getMessage());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.ERROR);
    }
}
